package com.zhongxi.guoyuan.view.user.gift;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;
import com.umeng.socialize.media.UMWeb;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.gift.GiftActivity;
import com.zhongxi.guoyuan.entity.gift.GroupInfo;
import com.zhongxi.guoyuan.entity.gift.RefInfo;
import com.zhongxi.guoyuan.entity.gift.StoreInfo;
import com.zhongxi.guoyuan.entity.user.GiftResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.GlideCircleTransform;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.widget.webview.ArticleWebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pl.droidsonroids.gif.GifImageView;

public class GiftDetailActivity extends BaseActivity {

    private static final int MESSAGE_WHAT = 21;
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.giftDetail_top_Name)
    TextView giftDetailTopName;
    @Bind(R.id.wv)
    ArticleWebView webView;
    @Bind(R.id.tv_countEnd)
    TextView mTvCountEnd;
    @Bind(R.id.ll_countTime)
    LinearLayout mLlCountTime;
    @Bind(R.id.tv_hour)
    TextView mTvHour;
    @Bind(R.id.tv_minute)
    TextView mTvMinute;
    @Bind(R.id.tv_second)
    TextView mTvSecond;
    @Bind(R.id.giftDetail_top_time)
    TextView mGiftDetailTopTime;
    @Bind(R.id.tv_overTime)
    TextView mTvOverTime;
    @Bind(R.id.giftDetail_image)
    ImageView mGiftDetailImage;
    @Bind(R.id.tv_goodName)
    TextView mTvGoodName;
    @Bind(R.id.tv_customer)
    TextView mTvCustomer;
    @Bind(R.id.tv_gattr)
    TextView mTvGattr;
    @Bind(R.id.tv_groupNum)
    TextView mTvGroupNum;
    @Bind(R.id.tv_hd)
    TextView mTvHd;
    @Bind(R.id.ll_hd)
    LinearLayout mLlHd;
    @Bind(R.id.tv_md)
    TextView mTvMd;
    @Bind(R.id.ll_md)
    LinearLayout mLlMd;
    @Bind(R.id.tv_partner)
    TextView mTvPartner;
    @Bind(R.id.ll_partner)
    LinearLayout mLlPartner;
    @Bind(R.id.tv_two_hd)
    TextView mTvTwoHd;
    @Bind(R.id.tv_two_flag)
    TextView mTvTwoFlag;
    @Bind(R.id.tv_three_hd)
    TextView mTvThreeHd;
    @Bind(R.id.tv_three_flag)
    TextView mTvThreeFlag;
    @Bind(R.id.ll_imges)
    LinearLayout mLlImages;
    @Bind(R.id.iv_head)
    ImageView mIvHead;
    @Bind(R.id.iv_group1)
    ImageView mIvGroup1;
    @Bind(R.id.iv_group2)
    ImageView mIvGroup2;
    @Bind(R.id.tv_myself)
    TextView mTvMyself;
    @Bind(R.id.tv_remain_money)
    TextView mTvRemainMoney;
    @Bind(R.id.tv_hour2)
    TextView mTvHour2;
    @Bind(R.id.tv_minute2)
    TextView mTvMinute2;
    @Bind(R.id.tv_second2)
    TextView mTvSecond2;
    @Bind(R.id.tv_group)
    TextView mTvGroup;
    @Bind(R.id.tv_group_money)
    TextView mTvGroupMoney;
    @Bind(R.id.ll_group)
    LinearLayout mLlGroup;
    @Bind(R.id.tv_sure)
    TextView mTvSure;
    @Bind(R.id.myScrollView)
    ScrollView mMyScrollView;

    private GiftResult result;
    private String type;
    private PopupWindow popupWindow;
    private View popupWindow_view;
    private SHARE_MEDIA platform;
    private UMShareAPI mShareAPI;


    private String aid;
    public static final int resultGift = 1000;
    private GiftActivity activity;
    private int mFlag;
    private AlertDialog mDialog;
    private String response;


    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_gift_detail);
        ButterKnife.bind(this);
        mShareAPI = UMShareAPI.get(this);
        tvTitle.setText("秒杀团购详情");
        initWebView();
    }

    @Override
    protected void initData() {
        super.initData();
        type = "activity";
        aid = getIntent().getExtras().getString("aid");
        mFlag = getIntent().getIntExtra("flag", 0);
        getServer(Url.ACTIVITY_DETAIL, null, "&aid=" + aid, false, null, "get");
    }

    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebChromeClient(new WebChromeClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(webView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("activity".equals(type)) {
                this.response = response;
                result = gson.fromJson(response, GiftResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (0 == result.getUserType()) {
                    mLlGroup.setVisibility(View.GONE);
                    mTvSure.setText("我要参团");
                } else if (1 == result.getUserType()) {
                    mTvSure.setText("继续邀友参团");
                    mLlGroup.setVisibility(View.VISIBLE);
                } else {
                    mTvSure.setText("一键开团");
                    mLlGroup.setVisibility(View.VISIBLE);
                }
                JSONObject mObject = new JSONObject(response);
                setData(mObject.optJSONObject("participants"));
            } else if ("share".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            removeMessages(MESSAGE_WHAT);
            tearDown();
        }
    };

    private void tearDown() {
        try {
            if (!TextUtils.isEmpty(activity.getEtime())) {
                SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date mParse = mFormat.parse(activity.getEtime());
                long mRemainTime = (mParse.getTime() - System.currentTimeMillis()) / 1000;
                if (mRemainTime > 0) {
                    mTvCountEnd.setVisibility(View.GONE);
                    mLlCountTime.setVisibility(View.VISIBLE);
                    long mL1 = mRemainTime / 60;  //  分
                    long mL4 = mRemainTime - (mL1 * 60);
                    if (mL4 < 1L) {
                        mTvSecond.setText("00");
                        mTvSecond2.setText("00");
                    } else if (mL4 >= 1L && mL4 < 10L) {
                        mTvSecond.setText("0" + mL4);
                        mTvSecond2.setText("0" + mL4);
                    } else {
                        mTvSecond.setText(String.valueOf(mL4));
                        mTvSecond2.setText(String.valueOf(mL4));
                    }

                    long mL2 = mL1 / 60;   // 时
                    if (mL2 < 1L) {
                        mTvHour.setText("00");
                        mTvHour2.setText("00");
                    } else if (mL2 >= 1L && mL2 < 10L) {
                        mTvHour.setText("0" + mL2);
                        mTvHour2.setText("0" + mL2);
                    } else {
                        mTvHour.setText(String.valueOf(mL2));
                        mTvHour2.setText(String.valueOf(mL2));
                    }
                    if (mL1 < 1L) {
                        mTvMinute.setText("00");
                        mTvMinute2.setText("00");
                    } else {
                        long mL3 = mL1 - (mL2 * 60);
                        mTvMinute.setText(String.valueOf(mL3));
                        mTvMinute2.setText(String.valueOf(mL3));
                    }

                    mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT, 1000);
                } else {
                    mLlCountTime.setVisibility(View.GONE);
                    mTvCountEnd.setVisibility(View.VISIBLE);
                }
            } else {
                mLlCountTime.setVisibility(View.GONE);
                mTvCountEnd.setVisibility(View.VISIBLE);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(MESSAGE_WHAT);
    }

    private void startCount() {
        mHandler.removeMessages(MESSAGE_WHAT);
        mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT, 1000);
    }

    List<String> otherIcon = new ArrayList<>();

    private void setData(JSONObject object) {
        if (result != null) {
            activity = result.getActivity();
            if (null != activity && !"".equals(activity)) {
                giftDetailTopName.setText(activity.getName());
                startCount();
                if (null != activity.getDetailsinfo() && !"".equals(activity.getDetailsinfo())) {
                    webView.loadDataWithBaseURL(null, getNewContent(activity.getDetailsinfo()),
                            "text/html", "utf-8", null);
                }
                mGiftDetailTopTime.setText("活动截止时间 : " + activity.getEtime());
                if (CommonTool.TimeCompareTime(activity.getStime(), activity.getEtime()) > 0) {
                    mTvOverTime.setText("还剩 " + CommonTool.TimeCompareTime(activity.getStime(), activity.getEtime()) + " 天");
                } else {
                    mTvOverTime.setText("该活动结束");
                }
                if (!TextUtils.isEmpty(activity.getGattr())) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(activity.getGattr());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Iterator<String> keys = jsonObject.keys();
                    String attr = "";
                    while (keys.hasNext()) {
                        String next = keys.next();
                        String attrValue = jsonObject.optString(next);
                        attr += attrValue + "/";
                    }
                    mTvGattr.setText(attr.substring(0, attr.length() - 1));
                } else {
                    mTvGattr.setText("");
                }

                if (!TextUtils.isEmpty(activity.getRedbeanfparticipants())) {
                    mLlHd.setVisibility(View.VISIBLE);
                    mTvHd.setText("奖 " + activity.getRedbeanfparticipants() + " 红豆");
                } else {
                    mLlHd.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(activity.getInnerfparticipants())) {
                    mLlMd.setVisibility(View.VISIBLE);
                    mTvMd.setText("奖 " + activity.getInnerfparticipants() + " 美豆");
                } else {
                    mLlMd.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(activity.getCpfparticipants())) {
                    mLlPartner.setVisibility(View.VISIBLE);
                    mTvPartner.setText("奖 " + activity.getCpfparticipants() + " 点合伙人分润权");
                } else {
                    mLlPartner.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(String.valueOf(activity.getTwogroupback()))) {
                    mTvTwoHd.setText(activity.getTwogroupback() + " 元");
                } else {
                    mTvTwoFlag.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(String.valueOf(activity.getThreegroupback()))) {
                    mTvThreeHd.setText(activity.getThreegroupback() + " 元");
                } else {
                    mTvThreeFlag.setVisibility(View.GONE);
                }
                mTvGroupMoney.setText(activity.getAprice() + " 元");
            }
            RefInfo mRefInfo = result.getRefInfo();
            if (mRefInfo != null && !"".equals(mRefInfo)) {
                Glide.with(UiUtils.getContext()).load(Url.IMG_URL + mRefInfo.getImages())
                        .placeholder(R.mipmap.iv_loading).into(mGiftDetailImage);
                mTvGoodName.setText(mRefInfo.getName());
                mTvMyself.setText("单独购 : " + mRefInfo.getMarketprice() + " 元");
                mTvMyself.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                mTvRemainMoney.setText("立省 " +
                        DataUtil.subtract(mRefInfo.getMarketprice(), activity.getAprice()) + " 元");
            }

            GroupInfo mGroupInfo = result.getGroupInfo();
            if (mGroupInfo != null && !"".equals(mGroupInfo)) {
                if (!TextUtils.isEmpty(mGroupInfo.getId())) {
                    mTvGroupNum.setText(mGroupInfo.getMembersnum() + " 人已开团");
                    mTvTwoFlag.setVisibility(View.VISIBLE);
                    if (mGroupInfo.getTwogroupisback() > 0) {
                        mTvTwoFlag.setText("(已返还)");
                        mTvTwoFlag.setTextColor(UiUtils.getColor(R.color.title_red));
                    } else {
                        mTvTwoFlag.setText("(未返还)");
                        mTvTwoFlag.setTextColor(UiUtils.getColor(R.color.bg_yield));
                    }
                    mTvThreeFlag.setVisibility(View.VISIBLE);
                    if (mGroupInfo.getThreegroupisback() == 1) {
                        mTvThreeFlag.setText("(已返还)");
                        mTvThreeFlag.setTextColor(UiUtils.getColor(R.color.title_red));
                    } else {
                        mTvThreeFlag.setText("(未返还)");
                        mTvThreeFlag.setTextColor(UiUtils.getColor(R.color.bg_yield));
                    }
                    if (null != object && !"".equals(object)) {

                        mLlImages.setVisibility(View.VISIBLE);
//                        Glide.with(UiUtils.getContext())
//                                .load(Url.BASE_URL + object.optString(mGroupInfo.getUserid()))
//                                .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
//                                .into(mIvHead);

                        Iterator<String> mIterator = object.keys();
                        while (mIterator.hasNext()) {
                            String mNext = mIterator.next();
                            String value = object.optString(mNext);
                            if (mNext.equals(mGroupInfo.getUserid())) {
                                setIcon(value, mIvHead);
                            } else {
                                otherIcon.add(value);
                            }
                        }

                        if (otherIcon.size() == 1) {
                            setIcon(otherIcon.get(0), mIvGroup1);
                        } else if (otherIcon.size() == 2) {
                            setIcon(otherIcon.get(0), mIvGroup1);
                            setIcon(otherIcon.get(1), mIvGroup2);
                        }

                    } else {
                        mLlImages.setVisibility(View.GONE);
                    }
                } else {
                    mLlImages.setVisibility(View.GONE);
                    mTvTwoFlag.setVisibility(View.GONE);
                    mTvThreeFlag.setVisibility(View.GONE);
                }
            } else {
                mTvTwoFlag.setVisibility(View.GONE);
                mTvThreeFlag.setVisibility(View.GONE);
                mLlImages.setVisibility(View.GONE);
            }
        }
    }

    private void setIcon(String value, ImageView imageView) {
        if (value.startsWith("http://") || value.startsWith("https://")) {
            Glide.with(UiUtils.getContext())
                    .load(value)
                    .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
                    .into(imageView);
        } else {
            Glide.with(UiUtils.getContext())
                    .load(Url.BASE_URL + value)
                    .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
                    .into(imageView);
        }
    }


    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (1001 == result.getCode()) {
                Toast.makeText(context, "用户未登录", Toast.LENGTH_LONG);
                finish();
            } else if (6001 == result.getCode()) {
                Toast.makeText(this, "库存不足", Toast.LENGTH_LONG).show();
                finish();
            } else if (6002 == result.getCode()) {
                Toast.makeText(this, "活动未开始", Toast.LENGTH_LONG).show();
                finish();
            } else if (6003 == result.getCode()) {
                Toast.makeText(this, "活动已停止", Toast.LENGTH_LONG).show();
                finish();
            } else if (6004 == result.getCode()) {
                Toast.makeText(this, "店铺 或商家已下架， 活动停止", Toast.LENGTH_LONG).show();
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if (4 == mFlag) {
            startAct(MainHomeActivity.class);
        }
        super.onBackPressed();
    }

    @OnClick({R.id.ivBack, R.id.tv_customer, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                if (4 == mFlag) {
                    startAct(MainHomeActivity.class);
                }
                finish();
                break;
            case R.id.tv_customer:
                popupWindowStoreInfo(1);
                break;
            case R.id.tv_sure:
                if (result.getUserType() == 1) {
                    if (!TextUtils.isEmpty(result.getShareKey())) {
                        UMMin umMin = new UMMin("gh_b944d829971d");
                        UMImage imagelocal = new UMImage(UiUtils.getContext(), R.mipmap.logo);
                        umMin.setThumb(imagelocal);
                        umMin.setTitle(activity.getName().trim());
                        umMin.setDescription(activity.getSubject().trim());
                        umMin.setPath("/pages/seckilldtl/seckilldtl?id=" + activity.getId() + "&sharekey=" + result.getShareKey());
                        umMin.setUserName("gh_b944d829971d");  // 原始id  -->小程序提供
                        new ShareAction(this)
                                .withMedia(umMin)
                                .setPlatform(SHARE_MEDIA.WEIXIN)
                                .setCallback(new UMShareListener() {
                                    @Override
                                    public void onStart(SHARE_MEDIA share_media) {

                                    }

                                    @Override
                                    public void onResult(SHARE_MEDIA share_media) {
                                        ToastUtil.show("分享成功了");
                                    }

                                    @Override
                                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                                    }

                                    @Override
                                    public void onCancel(SHARE_MEDIA share_media) {

                                    }
                                }).share();
                    } else {
                        ToastUtil.show("暂无分享功能,敬请期待!");
                    }
                } else if (result.getUserType() == 2) {
                    popupWindowStoreInfo(2);
                }
//                //分享
//                if (null != popupWindow && popupWindow.isShowing()) {
//                    popupWindow.dismiss();
//                } else {
//                    initPopuWindow();
//                }
                break;
        }
    }

    private void popupWindowStoreInfo(int i) {
        mDialog = new AlertDialog.Builder(this, R.style.Translucent_NoTitle).create();
        View view = UiUtils.inflate(R.layout.dialog_gift_detail);
        TextView shopName = (TextView) view.findViewById(R.id.tvShopName);
        TextView tv_tel = (TextView) view.findViewById(R.id.tv_tel);
        TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
        TextView tv_address = (TextView) view.findViewById(R.id.tv_address);
        LinearLayout ll_bottom = (LinearLayout) view.findViewById(R.id.ll_bottom);
        LinearLayout ll_self = (LinearLayout) view.findViewById(R.id.ll_self);
        LinearLayout ll_postage = (LinearLayout) view.findViewById(R.id.ll_postage);
        TextView tv_postage = (TextView) view.findViewById(R.id.tv_postage);
        ImageView iv_dimess = (ImageView) view.findViewById(R.id.iv_dimess);
        switch (i) {
            case 1:
                tv_phone.setVisibility(View.VISIBLE);
                ll_bottom.setVisibility(View.GONE);
                break;
            case 2:
                tv_phone.setVisibility(View.GONE);
                ll_bottom.setVisibility(View.VISIBLE);
                break;
        }
        iv_dimess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        final StoreInfo mStoreInfo = result.getStoreInfo();
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
        shopName.setText(mStoreInfo.getName());
        tv_tel.setText(mStoreInfo.getMphone());
        tv_address.setText(mStoreInfo.getAddress());
        tv_postage.setText("(快递费" + activity.getPostage() + "元)");
        tv_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mStoreInfo.getMphone())) {
                    mDialog.dismiss();
                    Intent mIntent = new Intent(Intent.ACTION_DIAL);
                    Uri mParse = Uri.parse("tel:" + mStoreInfo.getMphone());
                    mIntent.setData(mParse);
                    startActivity(mIntent);
                } else {
                    ToastUtil.show("暂时无法联系!");
                }
            }
        });
        switch (activity.getGetermethod()) {
            case 0:
                ll_self.setVisibility(View.VISIBLE);
                ll_postage.setVisibility(View.VISIBLE);
                break;
            case 1:  // 邮寄
                ll_self.setVisibility(View.GONE);
                ll_postage.setVisibility(View.VISIBLE);
                break;
            case 2:  //自提
                ll_self.setVisibility(View.VISIBLE);
                ll_postage.setVisibility(View.GONE);
                break;
        }
        ll_self.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                if (null != result && !"".equals(result)) {
                    Intent mIntent = new Intent(GiftDetailActivity.this, JoinGroupActivity.class);
                    mIntent.putExtra("result", result);
                    mIntent.putExtra("postFlay", 2);  // 自提
                    mIntent.putExtra("response", response);
                    startActivity(mIntent);
                } else {
                    ToastUtil.show("暂无数据,敬请期待!");
                }
            }
        });

        ll_postage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                if (null != result && !"".equals(result)) {
                    Intent mIntent = new Intent(GiftDetailActivity.this, JoinGroupActivity.class);
                    mIntent.putExtra("result", result);
                    mIntent.putExtra("postFlay", 1);
                    mIntent.putExtra("response", response);
                    startActivity(mIntent);
                } else {
                    ToastUtil.show("暂无数据,敬请期待!");
                }
            }
        });

        mDialog.setView(view);
        mDialog.show();
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(mTvSure, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }

                UMWeb mUMWeb = new UMWeb(Url.BASE_URL + "/activity/giftpacks/index/?sharekey=" + result.getShareKey());
                mUMWeb.setTitle(result.getActivity().getName());
                mUMWeb.setDescription(result.getActivity().getSubject());
                mUMWeb.setThumb(new UMImage(GiftDetailActivity.this, R.mipmap.logo));
                new ShareAction(GiftDetailActivity.this).setPlatform(platform)
                        .setCallback(umShareListener)
                        .withMedia(mUMWeb)
                        .share();

                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功了!!!");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.i("base", "fail");
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Log.i("base", "cancel");
            showShortToast("分享取消了");
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private String getNewContent(String htmltext) {

        String html = "<meta name=\"viewport\" content=\"width=device-width\"><div><p>";

//      <p ><img src = "https://z1admin.511b5.com/ueditor/php/upload/image/20180420/1524213052204464.jpg"
//        title = "1524213052204464.jpg" alt = "3.jpg" / ></p >
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");

        }
        Elements elements2 = doc.getElementsByTag("img");
        for (Element element : elements2) {
            element.attr("width", "100%").attr("height", "auto");
        }

        return doc.toString();
    }
}
